package net.lcheng.manage.controller;

import net.lcheng.commons.utils.PageList;
import net.lcheng.manage.utils.ControllerUtils;
import net.lcheng.manage.vo.PermissionsAddModel;
import net.lcheng.manage.vo.RoleAddModel;
import net.lcheng.manage.vo.SysUserAddModel;
import net.lcheng.model.*;
import net.lcheng.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by qiliping on 15/12/16.
 * 系统用户管理
 */
@Controller
public class SysUserController {
    @Autowired
    private SysRolesService rolesService;
    @Autowired
    private SysPermissionsService permissionsService;
    @Autowired
    private SysRolePermissionsService rolePermissionsService;
    @Autowired
    private SysUsersService usersService;
    @Autowired
    private SysUserRolesService userRolesService;

    private final int PAGESIZE = 10;
    /**
     * 后台角色管理
     * */
    @RequiresPermissions("sys:role_list")
    @RequestMapping(value = "/sys/role_list", method = RequestMethod.GET)
    public String roleList(Model model, HttpServletRequest request){
        ControllerUtils.common(model,permissionsService,"sys:role_list");

        List<SysRoles> roles = rolesService.getRoleList();
        model.addAttribute("roles",roles);
//        model.addAttribute("sub","role_list");
        return "sys/role_list";
    }
    /**
     * 添加后台角色GET
     * */
    @RequiresPermissions("sys:role_add")
    @RequestMapping(value = "/sys/role_add", method = RequestMethod.GET)
    public String roleAddGet(Model model){
        ControllerUtils.common(model,permissionsService,"sys:role_list");

        if (!model.containsAttribute("RoleAddModel")) {
            RoleAddModel addModel = new RoleAddModel();
            model.addAttribute("RoleAddModel", addModel);
        }

        List<SysPermissionsModel> list= permissionsService.getList();

        model.addAttribute("list",list);
//        model.addAttribute("sub","role_list");
        return "sys/role_add";
    }

    /**
     * 添加后台角色POST
     * */
    @RequiresPermissions("sys:role_add")
    @RequestMapping(value = "/sys/role_add", method = RequestMethod.POST)
    public String roleAddPost(Model model, @Valid @ModelAttribute("RoleAddModel") RoleAddModel addModel, BindingResult result){
        ControllerUtils.common(model,permissionsService,"sys:role_list");

        if (result.hasErrors()) {
            List<SysPermissionsModel> list= permissionsService.getList();
            model.addAttribute("list",list);
//            model.addAttribute("sub","role_list");
            return "sys/role_add";
        }
        int returnId = rolesService.addRole(addModel.getRoleName(),addModel.getRoleKey(),addModel.getRolePermissionKeys());
        if(returnId > 0) {
            return "redirect:/sys/role_list";
        }else{
            model.addAttribute("error","系统异常");
            return "redirect:/error";
        }
    }

    /**
     * 修改后台角色GET
     * */
    @RequiresPermissions("sys:role_edit")
    @RequestMapping(value = "/sys/role_edit/{id}", method = RequestMethod.GET)
    public String roleEditGet(Model model, @PathVariable(value="id") Integer id){
        ControllerUtils.common(model,permissionsService,"sys:role_list");

        //获取角色信息
        SysRoles roles = rolesService.getRoleById(id);
        //获取角色权限
        List<SysRolePermissions> permissions = rolePermissionsService.getPermissionsByRoleId(id);
        String[] rolePermissionKeys = new String[permissions.size()];
        for (int i=0;i<permissions.size();i++){
            rolePermissionKeys[i] = permissions.get(i).getPermissionKey();
        }

        if (!model.containsAttribute("RoleAddModel")) {
            RoleAddModel addModel = new RoleAddModel();
            addModel.setRoleName(roles.getRoleName());
            addModel.setRoleKey(roles.getRoleKey());
            addModel.setRolePermissionKeys(rolePermissionKeys);
            model.addAttribute("RoleAddModel", addModel);
        }

        List<SysPermissionsModel> list= permissionsService.getList();

        model.addAttribute("list",list);
//        model.addAttribute("sub","role_list");
        return "sys/role_add";
    }

    /**
     * 修改后台角色POST
     * */
    @RequiresPermissions("sys:role_edit")
    @RequestMapping(value = "/sys/role_edit/{id}", method = RequestMethod.POST)
    public String roleEditPost(Model model, @PathVariable(value="id") Integer id, @Valid @ModelAttribute("RoleAddModel") RoleAddModel addModel, BindingResult result){
        ControllerUtils.common(model,permissionsService,"sys:role_list");

        if (result.hasErrors()) {
            List<SysPermissionsModel> list= permissionsService.getList();
            model.addAttribute("list",list);
//            model.addAttribute("sub","role_list");
            return "sys/role_add";
        }
        System.out.println("权限列表:");
        for (String i:addModel.getRolePermissionKeys()
             ) {
            System.out.println(i);
        }
        System.out.println("权限列表END");
        //修改
        int returnId = rolesService.editRole(id,addModel.getRoleName(),addModel.getRoleKey(),addModel.getRolePermissionKeys());

        if(returnId > 0) {
            return "redirect:/sys/role_list";
        }else{
            model.addAttribute("error","系统异常");
            return "redirect:/error";
        }
    }

    /**
     * 删除后台角色GET
     * */
    @RequiresPermissions("sys:role_del")
    @RequestMapping(value = "/sys/role_del/{id}", method = RequestMethod.GET)
    public String roleDeleteGet(Model model, @PathVariable(value="id") Integer id,RedirectAttributes attributes){
        ControllerUtils.common(model,permissionsService,"sys:role_list");

        //获取角色信息
        SysRoles roles = rolesService.getRoleById(id);
        if(roles==null){
            attributes.addFlashAttribute("error","参数错误");
            return "redirect:/sys/role_list";
        }

        if(roles.getRoleKey().equals("admin")){
            attributes.addFlashAttribute("error","不能删除该数据");
            return "redirect:/sys/role_list";
        }
        //删除
        int returnId = rolesService.deleteRole(id);
        if(returnId >0){
            attributes.addFlashAttribute("error","操作成功");
        }else{
            attributes.addFlashAttribute("error","系统异常");
        }
        return "redirect:/sys/role_list";
    }


    /**
     * 后台用户管理
     * */
    @RequiresPermissions("sys:user_list")
    @RequestMapping(value = "/sys/user_list", method = RequestMethod.GET)
    public String userList(@RequestParam(defaultValue = "1", required = false) int page,Model model, HttpServletRequest request) {
        ControllerUtils.common(model,permissionsService,"sys:user_list");

        String name = request.getParameter("q");
        PageList<SysUsers> pageList = usersService.getUserList(page,PAGESIZE,name);
        model.addAttribute("list",pageList.list);
        model.addAttribute("q",name);
        model.addAttribute("pageIndex", page);
        model.addAttribute("totalPage", pageList.totalPage);
//        model.addAttribute("sub","user_list");
        return "sys/user_list";
    }

    /**
     * 添加后台用户GET
     * */
    @RequiresPermissions("sys:user_add")
    @RequestMapping(value = "/sys/user_add", method = RequestMethod.GET)
    public String userAddGet(Model model){
        ControllerUtils.common(model,permissionsService,"sys:user_list");

        if (!model.containsAttribute("SysUserAddModel")) {
            model.addAttribute("SysUserAddModel", new SysUserAddModel());
        }

        List<SysRoles> list = rolesService.getRoleList();
        model.addAttribute("roleList",list);
//        model.addAttribute("sub","user_list");
        return "sys/user_add";
    }

    /**
     * 添加后台用户POST
     * */
    @RequiresPermissions("sys:user_add")
    @RequestMapping(value = "/sys/user_add", method = RequestMethod.POST)
    public String userAddPost(Model model, @Valid @ModelAttribute("SysUserAddModel") SysUserAddModel addModel, BindingResult result,RedirectAttributes attributes){
        ControllerUtils.common(model,permissionsService,"sys:user_list");

        if(result.hasErrors()){
            List<SysRoles> list = rolesService.getRoleList();
            model.addAttribute("roleList",list);
//            model.addAttribute("sub","user_list");
            return "sys/user_add";
        }
        //查询用户是否存在
        SysUsers tempUser = usersService.getUserByUsername(addModel.getUserName());
        if(tempUser!=null) {
            result.rejectValue("userName", "error.addModel", "用户名已存在.");
            return "sys/user_add";
        }
        //添加用户
        int returnId = usersService.addUser(addModel.getUserName(),
                addModel.getPassword(),
                addModel.getEmail(),
                addModel.getTrueName(),
                addModel.getJobNo(),
                addModel.getDepartment(),
                addModel.getPhone(),
                addModel.getRoleIds());

        if(returnId >0){
            attributes.addFlashAttribute("error","操作成功");
        }else{
            attributes.addFlashAttribute("error","系统异常");
        }
        return "redirect:/sys/user_list";
    }

    private void initUserEditView(Model model,int userId){
        //获取用户信息
        SysUsers user = usersService.getUserByUserId(userId);

        List<SysUserRoles> userRoles = userRolesService.getUserRolesByUserId(userId);
        Integer[] roleIds = new Integer[userRoles.size()];
        for (int i=0;i<userRoles.size();i++){
            roleIds[i] = userRoles.get(i).getRoleId();
        }

        if (!model.containsAttribute("SysUserAddModel")) {
            SysUserAddModel addModel = new SysUserAddModel();
            addModel.setUserName(user.getUsername());
            addModel.setTrueName(user.getTrueName());
            addModel.setDepartment(user.getDepartment());
            addModel.setEmail(user.getEmail());
            addModel.setJobNo(user.getJobNo());
            addModel.setPhone(user.getPhone());
            addModel.setUserName(user.getUsername());
            addModel.setRoleIds(roleIds);
            model.addAttribute("SysUserAddModel", addModel);
        }

        List<SysRoles> list = rolesService.getRoleList();
        model.addAttribute("roleList",list);
        model.addAttribute("sub","user_list");
    }

    /**
     * 修改后台用户GET
     * */
    @RequiresPermissions("sys:user_edit")
    @RequestMapping(value = "/sys/user_edit/{id}", method = RequestMethod.GET)
    public String userEditGet(Model model,@PathVariable(value="id") Integer id,RedirectAttributes attributes){
        ControllerUtils.common(model,permissionsService,"sys:user_list");

        initUserEditView(model,id);
        return "sys/user_edit";
    }

    /**
     * 修改后台用户POST
     * */
    @RequiresPermissions("sys:user_edit")
    @RequestMapping(value = "/sys/user_edit/{id}", method = RequestMethod.POST)
    public String userEditPost(Model model, @PathVariable(value="id") Integer id, @Valid @ModelAttribute("SysUserAddModel") SysUserAddModel addModel, BindingResult result,RedirectAttributes attributes){
        ControllerUtils.common(model,permissionsService,"sys:user_list");

        if(result.hasFieldErrors("roleIds")){
            initUserEditView(model,id);
        }

        //修改
        int returnId = usersService.editUser(id,addModel.getPassword(),addModel.getEmail(),
                addModel.getTrueName(),addModel.getJobNo(),
                addModel.getDepartment(),
                addModel.getPhone(),
                addModel.getRoleIds());

        if(returnId >0){
            attributes.addFlashAttribute("error","操作成功");
        }else{
            attributes.addFlashAttribute("error","系统异常");
        }
        return "redirect:/sys/user_list";
    }

    /**
     * 删除后台用户
     * */
    @RequiresPermissions("sys:user_del")
    @RequestMapping(value = "/sys/user_del/{id}", method = RequestMethod.GET)
    public String userDeleteGet(Model model, @PathVariable(value="id") Integer id,RedirectAttributes attributes){
        ControllerUtils.common(model,permissionsService,"sys:user_list");

        //获取用户信息
        SysUsers user = usersService.getUserByUserId(id);
        if(user==null){
            attributes.addFlashAttribute("error","参数错误");
            return "redirect:/sys/user_list";
        }

        if(user.getUsername().equals("admin")){
            attributes.addFlashAttribute("error","不能删除该数据");
            return "redirect:/sys/user_list";
        }
        //删除
        int returnId = usersService.deleteUser(id);
        if(returnId >0){
            attributes.addFlashAttribute("error","操作成功");
        }else{
            attributes.addFlashAttribute("error","系统异常");
        }
        return "redirect:/sys/user_list";
    }

    /***
     * 后台权限列表
     * @param model
     * @return
     */
    @RequiresPermissions("sys:permissions_list")
    @RequestMapping(value = "/sys/permissions_list",method = RequestMethod.GET)
    public String permissions(Model model){
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser.isAuthenticated()) model.addAttribute("userName",currentUser.getPrincipals());

        List<SysPermissionsModel> list = permissionsService.getList();
        model.addAttribute("list",list);
        return "/sys/permissions_list";
    }

    /***
     * 添加GET
     * @param model
     * @return
     */
    @RequiresPermissions("sys:permissions_add")
    @RequestMapping(value = "/sys/permissions_add",method = RequestMethod.GET)
    public String permissionsAdd(Model model){
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser.isAuthenticated()) model.addAttribute("userName",currentUser.getPrincipals());
        List<SysPermissions> modelList = permissionsService.getModel();
        model.addAttribute("modelList",modelList);

        if (!model.containsAttribute("PermissionsAddModel")) {
            model.addAttribute("PermissionsAddModel", new PermissionsAddModel());
        }
        return "/sys/permissions_add";
    }

    /***
     * 获取菜单
     * @param modelId
     * @return
     */
    @RequiresPermissions("sys:permissions_add")
    @ResponseBody
    @RequestMapping(value = "/sys/permissions/get_menu_by_model")
    public List<SysPermissions> getMenuByModel(@RequestParam int modelId){
        List<SysPermissions> modelList = permissionsService.getMenuByModel(modelId);
        return modelList;
    }

    /***
     * 添加权限点
     * @param model
     * @param addModel
     * @param result
     * @return
     */
    @RequiresPermissions("sys:permissions_add")
    @RequestMapping(value = "/sys/permissions_add",method = RequestMethod.POST)
    public String permissionsAddPost(Model model,@Valid @ModelAttribute("PermissionsAddModel") PermissionsAddModel addModel, BindingResult result){
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser.isAuthenticated()) model.addAttribute("userName",currentUser.getPrincipals());

        if(result.hasErrors()){
            List<SysPermissionsModel> list = permissionsService.getList();
            model.addAttribute("list",list);
            return "/sys/permissions_add";
        }

        int returnResult = permissionsService.add(addModel.getName(),addModel.getKey(),addModel.getUrl(),addModel.getModel(),addModel.getMenu());
        if(returnResult>0){
            model.addAttribute("error","添加成功");
        }else model.addAttribute("error","系统异常");

            return "redirect:/sys/permissions_list";
    }

    @RequiresPermissions("sys:permissions_edit")
    @RequestMapping(value = "/sys/permissions_edit",method = RequestMethod.GET)
    public String permissionsEdit(Model model,@RequestParam int id){
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser.isAuthenticated()) model.addAttribute("userName",currentUser.getPrincipals());

        List<SysPermissions> modelList = permissionsService.getModel();
        model.addAttribute("modelList",modelList);
        SysPermissions permissions = permissionsService.getById(id);
        if(permissions.getModelId()>0){
            List<SysPermissions> menuList = permissionsService.getMenuByModel(permissions.getModelId());
            model.addAttribute("menuList",menuList);
        }
        PermissionsAddModel addModel = new PermissionsAddModel();
        addModel.setName(permissions.getName());
        addModel.setKey(permissions.getPermissionKey());
        addModel.setModel(permissions.getModelId());
        addModel.setMenu(permissions.getParentId());

        if (!model.containsAttribute("PermissionsAddModel")) {
            model.addAttribute("PermissionsAddModel", addModel);
        }
        return "/sys/permissions_add";
    }


    @RequiresPermissions("sys:permissions_edit")
    @RequestMapping(value = "/sys/permissions_edit",method = RequestMethod.POST)
    public String permissionsEditPost(Model model,@Valid @ModelAttribute("PermissionsAddModel") PermissionsAddModel addModel, BindingResult result){
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser.isAuthenticated()) model.addAttribute("userName",currentUser.getPrincipals());

        if(result.hasErrors()){
            List<SysPermissionsModel> list = permissionsService.getList();
            model.addAttribute("list",list);
            return "/sys/permissions_add";
        }
        int returnResult = permissionsService.edit(addModel.getId(),addModel.getName(),addModel.getKey(),addModel.getUrl(),addModel.getModel(),addModel.getMenu());

        if(returnResult>0){
            model.addAttribute("error","修改成功");
        }else model.addAttribute("error","系统异常");
        return "redirect:/sys/permissions_list";
    }
}
